package com.ruoyi.system.service;

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class BaiduImageRecognitionService {

    // 百度API Key和Secret Key
//    @Value("${baidu.api.key}")
    private static final String apiKey = "bce-v3/ALTAK-gxNxkfdUK4Eq7a8nGvhUH/520da3a1b1791ddf8004a46a8c138c689e4535df";

//    @Value("${baidu.secret.key}")
    private static final String secretKey = "076e1ccd464446dc82c7c589161a9c6e";

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    // 调用百度图像识别 API
    public String recognizeObjectFromImage(File imageFile) throws IOException {
        // 将图片文件转换为Base64编码
        String base64Image = imageToBase64(imageFile);

        // 请求的JSON体
        String requestBody = String.format(
//                "{\"image\":\"%s\", \"top_num\": 1}",
                "{\"model\":\"ernie-4.5-8k-preview\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"image_url\",\"image_url\":{\"url\":\"%s\"}},{\"type\":\"text\",\"text\":\"请写出这个事物的英文单词，不需要其他描述词\"}]},{\"role\":\"assistant\",\"content\":\"apple\"}],\"temperature\":0.8,\"top_p\":0.8,\"penalty_score\":1,\"disable_search\":false,\"enable_citation\":false}",
                base64Image
        );

        // 设置请求体
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, requestBody);

        // 创建请求
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general")
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + getAccessToken())
                .method("POST", body)
                .build();

        // 执行请求并获取响应
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 解析响应数据
                String responseBody = response.body().string();
                return parseResponse(responseBody);
            } else {
                return "API请求失败";
            }
        }
    }

    // 获取百度AI的access token
    public String getAccessToken() {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String body = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    return jsonObject.getString("access_token");
                } catch (org.json.JSONException e) {
                    e.printStackTrace();
                    return ""; // 处理异常时返回空字符串
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }


    // 将图片转换为Base64编码
    public String imageToBase64(File imageFile) throws IOException {
        byte[] bytes = java.nio.file.Files.readAllBytes(imageFile.toPath());
        return java.util.Base64.getEncoder().encodeToString(bytes);
    }

    // 解析API响应，获取识别的物体名称
    private String parseResponse(String responseBody) {
        try {
            JSONObject jsonResponse = new JSONObject(responseBody);
            JSONArray result = jsonResponse.getJSONArray("result");
            if (result.length() > 0) {
                return result.getJSONObject(0).getString("keyword"); // 获取第一个识别到的物体名称
            } else {
                return "无法识别物体";
            }
        } catch (org.json.JSONException e) {
            e.printStackTrace();
            return "处理 JSON 时发生错误";
        }
    }
}
